/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.groupbuy.api.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiniu.util.StringUtils;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupProdDto;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupSkuDto;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupTeamDto;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupUserDto;
import com.yami.shop.groupbuy.comment.api.vo.ApiGroupTeamInfoVo;
import com.yami.shop.groupbuy.comment.model.GroupOrder;
import com.yami.shop.groupbuy.comment.service.GroupOrderService;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import com.yami.shop.groupbuy.comment.service.GroupSkuService;
import com.yami.shop.groupbuy.comment.service.GroupTeamService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.OrderItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * 拼团信息接口
 *
 * @author 小懒虫
 * @date 2019/9/2 9:01
 */
@RestController
@RequestMapping("/p/groupTeam")
@Api(tags = "拼团信息接口")
public class GroupTeamController {

    @Autowired
    private GroupTeamService groupTeamService;

    @Autowired
    private GroupOrderService groupOrderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ShopConfig shopConfig;

    @Autowired
    private GroupProdService groupProdService;

    @Autowired
    private GroupSkuService groupSkuService;

    @GetMapping("/info")
    @ApiOperation(value = "拼团详情", notes = "拼团详情,至少携带一个参数,查看拼团单（团队）信息")
    public ResponseEntity<ApiGroupTeamInfoVo> teamInfo(
            @ApiParam(value = "拼团团队ID") @RequestParam("groupTeamId") Long groupTeamId,
            @ApiParam(value = "订单编号") @RequestParam("orderNumber") String orderNumber) {
        // 通过订单编号获取团ID
        if (!StringUtils.isNullOrEmpty(orderNumber)) {
            GroupOrder groupOrder = groupOrderService.getOne(new LambdaQueryWrapper<GroupOrder>()
                    .eq(GroupOrder::getOrderNumber, orderNumber));
            if (Objects.nonNull(groupOrder) && Objects.nonNull(groupOrder.getGroupTeamId())) {
                groupTeamId = groupOrder.getGroupTeamId();
            }
        }

        // 获取拼团团队信息
        ApiGroupTeamDto groupTeam = groupTeamService.getApiGroupTeamDto(groupTeamId);
        if (groupTeam == null) {
            // 该拼团单不存在
            throw new YamiShopBindException("yami.group.order.no.exist");
        }

        // 获取参团的用户列表
        List<ApiGroupUserDto> groupUserList = groupOrderService.listApiGroupUserDto(groupTeamId);
        // 如果昵称为空则为机器人参团
        groupUserList.forEach(apiGroupUserDto -> apiGroupUserDto.setNickName(StrUtil.isBlank(apiGroupUserDto.getNickName()) ? "系统参团":apiGroupUserDto.getNickName()));
        // 获取商品信息
        ApiGroupProdDto groupProd = groupProdService.getApiGroupProdDto(groupTeam.getGroupProdId(), I18nMessage.getDbLang());
        if (groupProd == null) {
            // 活动商品不在正常状态
            throw new YamiShopBindException("yami.group.prod.status.error");
        }

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());
        groupProd.setPrice(orderItems.get(0).getPrice());
        groupProd.setProdPic(shopConfig.getDomain().getResourcesDomainName() + "/" + orderItems.get(0).getPic());
        groupProd.setProdName(orderItems.get(0).getProdName());

        // 获取SKU列表
        List<ApiGroupSkuDto> groupSkuList = groupSkuService.getApiByGroupActivityIdAndProdId(groupProd.getGroupActivityId(), groupProd.getProdId());

        // 获取团购订单信息
        String userId = SecurityUtils.getUser().getUserId();
        GroupOrder groupOrder = groupOrderService.getOne(new LambdaQueryWrapper<GroupOrder>()
                .eq(GroupOrder::getGroupTeamId, groupTeamId).eq(GroupOrder::getUserId, userId).eq(GroupOrder::getStatus, 1));

        // 拼装拼团详情信息
        ApiGroupTeamInfoVo infoVo = new ApiGroupTeamInfoVo();
        infoVo.setGroupTeam(groupTeam);
        infoVo.setApiGroupUserList(groupUserList);
        infoVo.setGroupProd(groupProd);
        infoVo.setGroupSkuList(groupSkuList);
        if (groupOrder != null) {
            infoVo.setOrderNumber(groupOrder.getOrderNumber());
        }

        return ResponseEntity.ok(infoVo);
    }

    @GetMapping("/joinUsers")
    @ApiOperation(value = "参团的用户列表", notes = "参团的用户列表")
    public ResponseEntity<List<ApiGroupUserDto>> joinGroupUsers(
            @ApiParam(value = "拼团团队ID", required = true) @RequestParam("groupTeamId") Long groupTeamId) {
        // 获取参团的用户列表
        List<ApiGroupUserDto> groupUserList = groupOrderService.listApiGroupUserDto(groupTeamId);
        return ResponseEntity.ok(groupUserList);
    }
}
